package com.zejson.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zejson.entity.User;
import com.zejson.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.lang.reflect.InvocationTargetException;


@Controller             //Controller class
@Scope("prototype")	    //generate a new instance for new request
@RequestMapping("login")
public class LoginController {

	@RequestMapping("")
	public String index() throws ClassNotFoundException {
		return "/templates/login/login";
	}
	
	@RequestMapping("/login.do")
	public ModelAndView userLogin(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
		ModelAndView model;
		if (request.getMethod().equals("POST")) {
			String Email = request.getParameter("e-mail");
			String password = request.getParameter("password");
			ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
			UserService userService = ((UserService) applicationContext.getBean("userService"));
			User user = (User) userService.getByProperty("Email", Email).get(0);
			if (user == null) {
				model = new ModelAndView("/templates/login/login");
				model.addObject("message", "Username not found.");
				return model;
			}
			else if(user.getPassword().equals(password)) {
				String username;
				username = user.getUsername();
				request.getSession().setAttribute("username", username);
				model = new ModelAndView(("/templates/index"));
				model.addObject("message","welcome");
				return model;
			}
			else {
				model = new ModelAndView("/templates/login/login");
				model.addObject("message", "password is error.");
				return model;
			}
			
		} else {
			model = new ModelAndView("/templates/login/login");
			model.addObject("message", "Unresolved method.");
			return model;
		}
	}
}
